from apps.education.student.baseViews import *
from apps.education.teacher.dao import TeacherDao
from apps.chat.message.functions import MessageFun
from apps.system.role.dao import RoleDao
from apps.user.dao import UserDao

class StudentViewSet(BaseStudentViewSet):
    def get_queryset(self):
        params = getRequestParams(self.request)
        _list = StudentDao().findAll()
        return _list

    @action(methods=['post'], detail=False)
    def getStudentInfo(self, request):
        params = getRequestParams(self.request)
        obj = StudentDao().findOneByFilters({"user": self.request.user.id})
        if obj:
            model = self.serializer_class(obj).data
            return Response(response_success(model))
        else:
            return Response(response_action(10001, '未认证'))
    
    # 学生认证接口
    @action(methods=['post'], detail=False)
    def studentAuth(self, request):
        params = getRequestParams(request)
        if params.get('id'):
            params['checkStatus'] = 'CHECKING'
            StudentDao().update(params.get('id'), params)
        else:
            params['checkStatus'] = 'CHECKING'
            params['user'] = request.user.id
            StudentDao().create(params)
        MessageFun().sendMessage(None, request.user, 'system', {'title': '系统通知', 'content': '您的认证资料已提交成功，等待管理员审核！！'})
        return Response(response_action(10001, '提交成功，等待管理员审核！'))
    
    # 查看认证状态
    @action(methods=['post'], detail=False)
    def checkAuthStatus(self, request):
        params = getRequestParams(self.request)
        student = StudentDao().findOneByFilters({"user": self.request.user.id})
        teacher = TeacherDao().findOneByFilters({"user": self.request.user.id})
        if student:
            return Response(response_success({'identity': 'student'}))
        elif teacher:
            return Response(response_success({'identity': 'teacher'}))
        else:
            return Response(response_action(10001, '未认证'))
        
    # 审核通过
    @action(methods=['post'], detail=False)
    def checkPassAction(self, request):
        params = getRequestParams(self.request)
        obj_id = params.get('obj_id')
        student = StudentDao().update(obj_id, {'checkStatus': 'PASS'})
        UserDao().update(student.user.id, {'role': RoleDao().findOneByFilters({'key': 'student'}).key})
        MessageFun().sendMessage(None, student.user, 'system', {'title': '系统通知', 'content': '您的认证资料已通过审核！'})
        return Response(response_success('操作成功'))
    
    # 审核拒绝
    @action(methods=['post'], detail=False)
    def checkRefuseAction(self, request):
        params = getRequestParams(self.request)
        obj_id = params.get('obj_id')
        student = StudentDao().update(obj_id, {'checkStatus': 'REFUSE', 'remark': params.get('remark')})
        MessageFun().sendMessage(None, student.user, 'system', {'title': '系统通知', 'content': '您的认证资料未通过！原因：' + student.remark})
        return Response(response_success('操作成功'))
